package com.lframework.jh.push.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.lframework.jh.push.core.components.resp.PageResult;
import com.lframework.jh.push.core.constants.StringPool;
import com.lframework.jh.push.core.exceptions.impl.DefaultClientException;
import com.lframework.jh.push.core.impl.BaseMpServiceImpl;
import com.lframework.jh.push.core.utils.*;
import com.lframework.jh.push.service.annotations.OpLog;
import com.lframework.jh.push.service.entity.Channel;
import com.lframework.jh.push.service.enums.OpLogType;
import com.lframework.jh.push.service.mappers.ChannelMapper;
import com.lframework.jh.push.service.service.ChannelService;
import com.lframework.jh.push.service.vo.channel.ChannelSelectorVo;
import com.lframework.jh.push.service.vo.channel.CreateChannelVo;
import com.lframework.jh.push.service.vo.channel.QueryChannelVo;
import com.lframework.jh.push.service.vo.channel.UpdateChannelVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Slf4j
@Service
public class ChannelServiceImpl extends BaseMpServiceImpl<ChannelMapper, Channel> implements ChannelService {

    @Override
    public PageResult<Channel> query(Integer pageIndex, Integer pageSize,
                                     QueryChannelVo vo) {

        Assert.greaterThanZero(pageIndex);
        Assert.greaterThanZero(pageSize);

        PageHelperUtil.startPage(pageIndex, pageSize);
        List<Channel> datas = this.query(vo);

        return PageResultUtil.convert(new PageInfo<>(datas));
    }

    @Override
    public List<Channel> query(QueryChannelVo vo) {

        return getBaseMapper().query(vo);
    }

    @Cacheable(value = Channel.CACHE_NAME, key = "#id", unless = "#result == null")
    @Override
    public Channel findById(String id) {

        return getBaseMapper().selectById(id);
    }

    @Cacheable(value = Channel.CACHE_NAME, key = "#code", unless = "#result == null")
    @Override
    public Channel findByCode(String code) {
        Wrapper<Channel> queryWrapper = Wrappers.lambdaQuery(Channel.class).eq(Channel::getCode, code);
        return this.getOne(queryWrapper);
    }

    @Override
    public PageResult<Channel> selector(Integer pageIndex, Integer pageSize,
                                        ChannelSelectorVo vo) {

        Assert.greaterThanZero(pageIndex);
        Assert.greaterThanZero(pageSize);

        PageHelperUtil.startPage(pageIndex, pageSize);
        List<Channel> datas = getBaseMapper().selector(vo);

        return PageResultUtil.convert(new PageInfo<>(datas));
    }

    @OpLog(type = OpLogType.CHANNEL, name = "新增渠道，ID：{}, 编号：{}, 名称：{}", params = {"#_result", "#vo.code", "#vo.name"}, autoSaveParams = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String create(CreateChannelVo vo) {

        Wrapper<Channel> checkWrapper = Wrappers.lambdaQuery(Channel.class)
                .eq(Channel::getCode, vo.getCode());
        if (getBaseMapper().selectCount(checkWrapper) > 0) {
            throw new DefaultClientException("编号重复，请重新输入！");
        }

        checkWrapper = Wrappers.lambdaQuery(Channel.class)
                .eq(Channel::getName, vo.getName());
        if (getBaseMapper().selectCount(checkWrapper) > 0) {
            throw new DefaultClientException("名称重复，请重新输入！");
        }

        if (!JsonUtil.isJsonArray(vo.getParams())) {
            throw new DefaultClientException("配置参数格式有误，请检查！");
        }

        Channel data = new Channel();
        data.setId(IdUtil.getId());
        data.setCode(vo.getCode());
        data.setName(vo.getName());
        data.setParams(vo.getParams());
        data.setAvailable(Boolean.TRUE);
        data.setDescription(
                StringUtil.isBlank(vo.getDescription()) ? StringPool.EMPTY_STR : vo.getDescription());

        getBaseMapper().insert(data);

        return data.getId();
    }

    @OpLog(type = OpLogType.CHANNEL, name = "修改渠道，ID：{}, 编号：{}, 名称：{}", params = {"#vo.id", "#vo.code", "#vo.name"}, autoSaveParams = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(UpdateChannelVo vo) {

        if ("false".equalsIgnoreCase(ApplicationUtil.getProperty("jh.allow-channel-modify"))) {
            throw new DefaultClientException("不允许修改渠道信息！");
        }

        Channel data = this.findById(vo.getId());
        if (ObjectUtil.isNull(data)) {
            throw new DefaultClientException("渠道不存在！");
        }

        if ("false".equalsIgnoreCase(ApplicationUtil.getProperty("jh.allow-channel-params-modify"))) {
            if (!StringUtil.equals(vo.getParams(), data.getParams())) {
                throw new DefaultClientException("不允许修改渠道参数配置！");
            }
        }

        Wrapper<Channel> checkWrapper = Wrappers.lambdaQuery(Channel.class)
                .eq(Channel::getCode, vo.getCode())
                .ne(Channel::getId, vo.getId());
        if (getBaseMapper().selectCount(checkWrapper) > 0) {
            throw new DefaultClientException("编号重复，请重新输入！");
        }

        checkWrapper = Wrappers.lambdaQuery(Channel.class)
                .eq(Channel::getName, vo.getName())
                .ne(Channel::getId, vo.getId());
        if (getBaseMapper().selectCount(checkWrapper) > 0) {
            throw new DefaultClientException("名称重复，请重新输入！");
        }

        if (!JsonUtil.isJsonArray(vo.getParams())) {
            throw new DefaultClientException("配置参数格式有误，请检查！");
        }

        LambdaUpdateWrapper<Channel> updateWrapper = Wrappers.lambdaUpdate(Channel.class)
                .set(Channel::getCode, vo.getCode())
                .set(Channel::getName, vo.getName())
                .set(Channel::getParams, vo.getParams())
                .set(Channel::getAvailable, vo.getAvailable())
                .set(Channel::getDescription,
                        StringUtil.isBlank(vo.getDescription()) ? StringPool.EMPTY_STR : vo.getDescription())
                .eq(Channel::getId, vo.getId());

        getBaseMapper().update(updateWrapper);
    }

    @CacheEvict(value = Channel.CACHE_NAME, key = "#key")
    @Override
    public void cleanCacheByKey(Serializable key) {

    }
}
